package util

import (
	"adam2/internal/model"
	"math"
)

// 计算最近一周的周线级别boll，参数为model.StockWeekArray类型
func CalculateLatestBollForStockWeekArray(stockWeekArray model.StockWeekArray) (float64, float64, float64) {
	// 计算20日移动平均线/中轨
	var sum float64 = 0
	var n float64 = 20
	var param float64 = 20
	for i := len(stockWeekArray) - 1; i >= 0; i-- {
		n--
		sum += stockWeekArray[i].ClosePrice
		if n == 0 {
			break
		}
	}
	var average float64 = sum / param

	// 计算上轨
	sum = 0
	n = 20
	for i := len(stockWeekArray) - 1; i >= 0; i-- {
		n--
		sum += math.Pow(stockWeekArray[i].ClosePrice-average, 2)
		if n == 0 {
			break
		}
	}
	var up = average + 2*math.Sqrt((sum/param))

	// 计算下轨
	sum = 0
	n = 20
	for i := len(stockWeekArray) - 1; i >= 0; i-- {
		n--
		sum += math.Pow(stockWeekArray[i].ClosePrice-average, 2)
		if n == 0 {
			break
		}
	}
	var dn = average - 2*math.Sqrt((sum/param))

	return up, average, dn
}

// 计算最近一周的周线级别boll，参数为model.CommodityFutureWeekDataArray类型
func CalculateLatestBollForCommodityFutureWeekDataArray(commodityFutureWeekDataArray model.CommodityFutureWeekDataArray) (float64, float64, float64) {
	// 计算20日移动平均线/中轨
	var sum float64 = 0
	var n float64 = 20
	var param float64 = 20
	for i := len(commodityFutureWeekDataArray) - 1; i >= 0; i-- {
		n--
		sum += commodityFutureWeekDataArray[i].ClosePrice
		if n == 0 {
			break
		}
	}
	var average float64 = sum / param

	// 计算上轨
	sum = 0
	n = 20
	for i := len(commodityFutureWeekDataArray) - 1; i >= 0; i-- {
		n--
		sum += math.Pow(commodityFutureWeekDataArray[i].ClosePrice-average, 2)
		if n == 0 {
			break
		}
	}
	var up = average + 2*math.Sqrt((sum/param))

	// 计算下轨
	sum = 0
	n = 20
	for i := len(commodityFutureWeekDataArray) - 1; i >= 0; i-- {
		n--
		sum += math.Pow(commodityFutureWeekDataArray[i].ClosePrice-average, 2)
		if n == 0 {
			break
		}
	}
	var dn = average - 2*math.Sqrt((sum/param))

	return up, average, dn
}
